#coding=utf-8

import yaml
import os
import sys
import json
import io
import subprocess
import logging

main_config = None
proj_config = None

def getMainConfig(full_key):
    global main_config

    if main_config == None:
        self_dir = os.path.dirname(os.path.abspath(__file__))
        self_dir = os.path.split(self_dir)[0]
    
        cfg_file = os.path.join(self_dir, 'config.yaml')

        if not os.path.exists(cfg_file):
            rc_group_dir =  os.path.dirname(os.path.dirname(self_dir))
            cfg_file = os.path.join(rc_group_dir, 'config.yaml')

        if os.path.exists(cfg_file):
            f = io.open(cfg_file, 'r', encoding = 'utf-8')
            f_data = f.read()
            f.close()
            main_config = yaml.full_load(f_data)
            if main_config == None:
                main_config = {}
        else:
            print(u"config.yaml 文件不存在，需要将 config.example.yaml 复制为 config.yaml 并进行配置")
            exit(1)

    ret = main_config
    key_list = full_key.split('.')
    for key in key_list:
        if key in ret:
            ret = ret[key]
        else:
            ret = None
            break
        
    return ret

def getProjectConfig(full_key, proj_name = None):
    global proj_config

    if proj_config == None:
        if proj_name == None:
            proj_name = getMainConfig('project.name')

        self_dir = os.path.dirname(os.path.abspath(__file__))
        self_dir = os.path.split(self_dir)[0]
        cfg_file = os.path.join(self_dir, 'config.' + proj_name + '.yaml')

        print(cfg_file)
        if not os.path.exists(cfg_file):
            print("config.yaml 文件不存在")
            exit(1)
        
        f = io.open(cfg_file, 'r', encoding = 'utf-8')
        f_data = f.read()
        f.close()
        proj_config = yaml.full_load(f_data)
        if proj_config == None:
            proj_config = {}

    ret = proj_config
    key_list = full_key.split('.')
    for key in key_list:
        if key in ret:
            ret = ret[key]
        else:
            ret = None
            break

    return ret


def getConfig(full_key):
    ret = getMainConfig(full_key)
    if ret == None:
        ret = getProjectConfig(full_key)

    return ret